<?php
namespace app\controllers\api\upload;

use Fate;
use fate\http\Request;
use app\libs\Uploader;
use app\libs\Util;

// 上传
class UploadController extends \fate\web\PureController {
    public function run() {
        $req = Request::getInstance();

        $uid = $req->getParameter('uid');
        $time = $req->getParameter('timestamp');
        $token = $req->getParameter('token');
        $projectId = $req->getParameter('project_id');
        $upbase = Util::plainText($req->getParameter('upbase'));

        // 合法性
        $calculate = md5(Fate::$app->securityKey . $uid . $time);

        if($calculate !== $token) {
            $this->ajaxReturn(null, 200003);
            exit;
        }
        if(!is_numeric($projectId)) {
            $this->ajaxReturn(null, 300002);
            exit;
        }
        if(!$upbase) {
            $this->ajaxReturn(null, 300002);
            exit;
        }

        $uploader = new Uploader();
        $uploader->setConfigs([
            'basePath' => '.' . $upbase
        ]);
        $uploader->uploadFile('editorfile');

        $img = $uploader->getFirstUploadedFile();
        if('' === $img) {
            $this->ajaxReturn(null, 300003);
            exit;
        }

        // and prefix
        $img = $upbase . $img;

        $this->ajaxReturn([
            'project_id' => $projectId,
            'uri' => $img
        ]);
    }
}
